import { RouteRecordRaw } from 'vue-router'
import { cloneDeep } from 'lodash-es'
import { transformI18n } from '@/plugins/i18n'
import { storeToRefs } from 'pinia'
import { useTagCacheStoreWithOut } from '@/store/storage/tagCacheStore'
import remainingRouter from '../remaining'
const routeComponentList = import.meta.glob('/src/views/**/**.vue')
const tagCacheStore = useTagCacheStoreWithOut()

// 路由白名单
export const routerWhiteList = {
  login: ['/Login', '/Pages/Exception/403', '/Pages/Exception/404', '/Pages/Exception/500', '/Pages/Exception/NetworkError', '/Pages/Exception/Developmenting', '/Pages/Exception/UpgradeRepair'], // 登录白名单
  selfScroll: ['EpInfiniteScrollList'], // 使用自身滚动条白名单
  multipleTag: ['SingleParamDetail', 'TagDetail', 'MultiParamsDetail', 'QueryDetail'], // 多标签页白名单
  root: ['PageDesign', 'DesignerPreview', 'PreviewFrame', 'BigScreen', 'BigScreenWorkstation', 'BigScreenPreview'] // 根路由白名单
}

// 后端字段转化为前端字段
export const menuFieldInvert = (data) => {
  const result = []
  data.forEach((item) => {
    result.push({
      id: item.id,
      pid: item.pid,
      title: item.title,
      icon: item.icon,
      url: item.url,
      path: item.path,
      redirect: item.redirect,
      showLink: item.showLink,
      sort: item.sort,
      route: item.route,
      transitionName: item.transitionName,
      keepAlive: item.keepAlive,
      isFixed: item.isFixed,
      isCatalog: item.isCatalog,
      badge: item.badge,
      hot: item.hot,
      status: item.status,
      permit: item.permit
    })
  })
  return result
}

// 菜单数据转化为规范化的路由格式数据
export const dataToRouteMenu = (item, isMenu) => {
  const { fixedTagList } = storeToRefs(tagCacheStore)
  return {
    path: item.url,
    name: item.route ? item.route : undefined,
    redirect: item.redirect ? item.redirect : '',
    component: !isMenu && item.path ? routeComponentList[`/src/views${item.path}/index.vue`] : undefined,
    meta: {
      id: item.id,
      pid: item.pid,
      icon: item.icon,
      title: item.title,
      keepAlive: item.keepAlive,
      isFixed: fixedTagList.value && fixedTagList.value.includes(item.url) ? true : item.isFixed,
      hot: item.hot,
      sort: item.sort,
      transitionName: item.transitionName,
      isCatalog: item.isCatalog,
      showLink: item.showLink,
      badge: item.badge,
      status: item.status,
      i18n: true,
      showTag: routerWhiteList.multipleTag.includes(item.route) ? 9 : routerWhiteList.root.includes(item.route) ? 0 : 1,
      isRoot: !!routerWhiteList.root.includes(item.route),
      permit: item.permit
    }
  }
}

/**
 * 将树形结构路由处理成一维数组
 * @param routesList 传入路由
 * @returns 返回处理后的一维路由
 */
export const routerTreeToFlattening = (routesList: RouteRecordRaw[]) => {
  if (routesList.length === 0) return routesList
  const newRouteList = []
  function flatteningRoute(routesList) {
    routesList.forEach(function (item) {
      const newItem = cloneDeep(item)
      newItem.children = []
      newRouteList.push(newItem)
      if (item.children && item.children.length > 0) {
        flatteningRoute(item.children)
      }
    })
  }
  flatteningRoute(routesList)
  return newRouteList
}

// 将规范路由的一维数组转为树形结构
export const routerToTree = (arrRoutes: any) => {
  const parents = arrRoutes.filter(function (item: any) {
    return item.meta.pid === 0
  })
  const children = arrRoutes.filter(function (item: any) {
    return item.meta.pid !== 0
  })
  if (parents.length > 0 && children.length > 0) {
    // 递归处理动态路由层级
    convert(parents, children)
    return parents
  } else {
    return parents
  }
}

// 递归处理动态路由层级
const convert = (parents: any, children: any) => {
  parents.forEach(function (item: any) {
    if (!item.meta.breadcrumb) {
      item.meta.breadcrumb = []
      const currentBreadcrumb = cloneDeep(item)
      currentBreadcrumb.component = null
      item.meta.breadcrumb.push(currentBreadcrumb)
    }
    item.children = []
    children.forEach(function (current: any, index: any) {
      if (current.meta.pid === item.meta.id) {
        current.meta.breadcrumb = cloneDeep(item.meta.breadcrumb)
        const currentSubBreadcrumb = cloneDeep(current)
        currentSubBreadcrumb.component = null
        currentSubBreadcrumb.meta.breadcrumb = []
        current.meta.breadcrumb.push(currentSubBreadcrumb)
        const temp = children.filter(function (v: any, idx: any) {
          return idx !== index
        }) // 删除已匹配项，这里未使用JSON.parse(JSON.stringify(children))是因为路由的component已经是函数形式，再格式化后，模块导入功能丢失，会导致找不到模块
        item.children.push(current)
        convert([current], temp) // 递归
      }
    })
  })
}

// 树形结构数据递归排序
export const treeToAscending = (arr: any) => {
  const newTree = ascending(arr)
  newTree.forEach(function (item: any) {
    if (item.children && item.children.length > 1) {
      item.children = ascending(item.children)
    }
  })
  return newTree
}

// 按照路由中meta下的sort等级升序来排序路由
const ascending = (arr: any) => {
  return arr.sort((a: any, b: any) => {
    return a?.meta?.sort - b?.meta?.sort
  })
}

// 修改已实例化路由的重定向
export const resetRouterRedirect = (router, routeList) => {
  const rootRouteList = routeList.filter((item) => {
    return item.meta.isRoot
  })
  const layoutRouteList = routeList.filter((item) => {
    return !item.meta.isRoot
  })
  const remainingRouterName = []
  remainingRouter.forEach((item) => {
    remainingRouterName.push(item.name)
  })
  router.options.routes.forEach((item) => {
    if (item.name === 'Layout') {
      if (layoutRouteList.length > 0) {
        item.redirect = layoutRouteList[0].path
      } else {
        if (rootRouteList.length > 0) {
          item.redirect = rootRouteList[0].path
        }
      }
      if (item.children && item.children.length > 0) {
        editRouteRedirect(item.children, routeList)
      } else {
        item.children = []
      }
    } else {
      if (!remainingRouterName.includes(item.name) && item.meta.isCatalog) {
        editRouteRedirect(item.children, routeList)
      }
    }
  })
}

// 重新修改已实例化路由的重定向
const editRouteRedirect = (data, routeList) => {
  data.forEach((item) => {
    if (item.meta.isCatalog) {
      const index = routeList.findIndex((v) => v.meta.id === item.meta.id)
      if (index >= 0) {
        item.redirect = routeList[index].redirect
      }
      editRouteRedirect(item.children, routeList)
    }
  })
}

// 重置目录层的重定向
export const resetRedirect = (data) => {
  data.forEach((item) => {
    if (item.meta.isCatalog) {
      // 此时目录层的children肯定有子级，因为上面已经把无子级的目录层删除
      item.redirect = item.children[0].path
      resetRedirect(item.children)
    }
  })
}

// 删除空的目录层
export const removeEmptyCatalog = (treeData) => {
  const traversal = (data) => {
    for (let i = 0; i < data.length; i++) {
      const info = data[i]
      if (info.children) {
        if (info.children.length > 0) {
          traversal(info.children)
        }
        if (info.children.length === 0 && info.meta.isCatalog) {
          const index = data.findIndex((item) => info.meta.id === item.meta.id)
          data.splice(index, 1)
          i--
        }
      }
    }
  }
  traversal(treeData)
}

// 根据路由name递归寻找选中的路由
export const findRouter = (router, routerName) => {
  let currentRoute: any = {}
  const checkRouter = (arr: object[], name) => {
    arr.forEach((arrItem: any) => {
      if (arrItem.name === name) {
        currentRoute = cloneDeep(arrItem)
        return
      } else {
        if (arrItem.children && arrItem.children.length > 0) {
          checkRouter(arrItem.children, name)
        }
      }
    })
  }
  checkRouter(router, routerName)
  return currentRoute
}

/**
 * 设置页面标题
 */
export const setPageTitle = (meta) => {
  if (meta.title) {
    document.title = transformI18n(('menus.' + meta.title) as string, meta.i18n as boolean) + ' - ' + transformI18n('settings.settingProjectTitle', true)
  } else {
    document.title = transformI18n('settings.settingProjectTitle', true)
  }
}
